#!/usr/bin/python
# -*- coding: utf-8 -*-
"""基于simplejson的json序列化和反序列化
"""

import datetime
try:
    import simplejson
except:
    from django.utils import simplejson
    
def dumps(o):
    """返回JSON序列化字符串(unicode)
       
    支持Datetime格式，但不能反序列化"""
    return simplejson.dumps(o, ensure_ascii=False, 
                            cls=DateTimeAwareJSONEncoder)

def loads(s):
    """JSON反序列化"""
    return simplejson.loads(s)


class DateTimeAwareJSONEncoder(simplejson.JSONEncoder):
    """
    JSONEncoder subclass that knows how to encode date/time types
    
    copy from django.core.serializers.json
    """
    
    DATE_FORMAT = "%Y-%m-%d" 
    TIME_FORMAT = "%H:%M:%S"
    
    def default(self, o):
        if isinstance(o, datetime.datetime):
            return o.strftime("%s %s" % (self.DATE_FORMAT, self.TIME_FORMAT))
        elif isinstance(o, datetime.date):
            return o.strftime(self.DATE_FORMAT)
        elif isinstance(o, datetime.time):
            return o.strftime(self.TIME_FORMAT)
        else:
            return super(DateTimeAwareJSONEncoder, self).default(o)
        
if __name__ == '__main__':
    l = [1, 0,
         None,
         True, False, 
         'str', u'unicode', '晕aaa', u'继a续晕', 
         {1:1, '2':'2', u'3':u'3'},
         datetime.datetime.now(),
         ]
    data = dumps(l)
    assert isinstance(data, unicode)
    print `data`
    print loads(data)
    assert loads(data)[:-2] == l[:-2]